import axios from 'axios';
import './eweisdk';

/* global BudoDubboHttpApiJavascriptSdk */
export const Apis = new BudoDubboHttpApiJavascriptSdk();
export const Config = {
  host: '',
  token: '',
  appKey: ''
};

const apiUrl = '/api2';

Apis.setDeferredFactory((request, sdk) => {
  request.parameters = {
    _token: Config.token,
    _app_key: Config.appKey
  };
  if (!Config.token) {
    // eslint-disable-next-line
    delete request.parameters._token;
  }
  if (!Config.appKey) {
    // eslint-disable-next-line
    delete request.parameters._app_key;
  }
  let params = '';
  let keys = Object.keys(request.parameters || {});
  for (let i = 0; i < keys.length; i++) {
    params += `${encodeURIComponent(keys[i])}=${encodeURIComponent(request.parameters[keys[i]])}`;
    if (i < (keys.length - 1)) params += '&';
  }

  let url = `${Config.host}${apiUrl}/${request.interfaceName}.${request.methodName}`;
  if (params) {
    url += `?${params}`;
  }
  let args = request.args.length > 0 ? request.args[0] : {}; // 无参数时以空对象进行序列化传输
  // eslint-disable-next-line
  request.requestBody = sdk._serialization.serialize(args); // 序列化

  return axios.post(url, request.requestBody || {}, {
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    if (res.data && res.data.status === 0) {
      return res.data.result;
    }
    return Promise.reject(res.data ? res.data.result : res.data);
  }, error => Promise.reject(error));
});

